﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Media;
using System.Threading;
using System.Web.UI;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;
using zymarc;

namespace zymain
{
    public partial class FrmGcExcelImp : Form
    {
        private string filePath = string.Empty;
        private BindingSource BookData;
        public string uid;
        public int kjm;
        private bool flag = false;
        private DataTable tabTemp = new DataTable();
        private DataTable dt = new DataTable();
        private string marcText;
        public FrmGcExcelImp()
        {
            InitializeComponent();
        }
        private void Fr_Shown(object sender, EventArgs e)
        {
            tabTemp.Columns.Add("字段标识");
            tabTemp.Columns.Add("指");
            tabTemp.Columns.Add("子字段");
            dt.Columns.Add("字段标识");
            dt.Columns.Add("指");
            dt.Columns.Add("子字段");
        }
        private void excelBtn_Click(object sender, EventArgs e)
        {
            //Console.WriteLine("库键码=" + kjm);
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Excel文件";
            ofd.FileName = "";
            //ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//为了获取特定的系统文件夹，可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举，其中可以定义要返回路径的哪个系统目录
            ofd.Filter = "Excel文件| *.xlsx";
            ofd.RestoreDirectory = true;//记录上次打开的目录
            ofd.Multiselect = false; //不允许选中多个文件
            ofd.ValidateNames = true;     //文件有效性验证ValidateNames，验证用户输入是否是一个有效的Windows文件名
            ofd.CheckFileExists = true;  //验证路径有效性
            ofd.CheckPathExists = true; //验证文件有效性
            string strName = string.Empty;
            if (string.IsNullOrEmpty(filePath))
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    strName = ofd.FileName;
                    filePath = strName;
                }
            }
            else
            {
                if (MessageBox.Show("确认要清除当前文件，重新加载吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    filePath = "";
                    listBox1.Items.Clear();
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        strName = ofd.FileName;
                        filePath = strName;
                    }
                }
            }
            if (strName == "")
            {
                MessageBox.Show("没有选择Excel文件！无法进行数据导入");
                return;
            }
            ExcelListBox(strName);
            if (this.listBox1.Items.Count > 0)
            {
                this.listBox1.SelectedIndex = 0;
            }
        }

        private void ExcelListBox(string excelpath)
        {
            string error;
            DataTable table = OfficeTool.OfficeExcelListBox(excelpath, out error);
            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    this.listBox1.Items.Add(table.Rows[i]["Table_Name"].ToString());
                }
            }
            else
            {
                if (!error.Equals("文件格式有误"))
                {
                    using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(excelpath, false))
                    {
                        WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
                        IEnumerable<Sheet> sheets = workbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                        int m = 0;
                        foreach (OpenXmlElement s in sheets)
                        {
                            foreach (OpenXmlAttribute attr in s.GetAttributes())
                            {
                                if (m % 3 == 0)//因为attr.Value中包含工作表名,工作表序号和ID号
                                {
                                    this.listBox1.Items.Add(attr.Value);//把工作表名装到List中
                                }
                                m++;
                            }
                        }
                    }
                }
            }
        }

        private DataTable ReadFromExcel(string excelpath, string listBox)
        {
            DataTable table = new DataTable();
            string sExt = System.IO.Path.GetExtension(excelpath);
            if (sExt == ".xlsx" || sExt == ".xls")
            {
                string error;
                table = OfficeTool.ReadOfficeExcel(excelpath, listBox, out error);
                if (table.Rows.Count == 0)
                {
                    if (string.IsNullOrEmpty(error) && !error.Equals("文件格式有误"))
                    {
                        table = OpenXMLHelper.ExcelWorksheetToDataTable(excelpath, listBox);
                    }
                }
                return table;
            }
            else
            {
                MessageBox.Show("文件格式有误");
                return null;
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            FrmWait wait = new FrmWait();
            wait.Show();
            wait.label4.Text = "";
            Application.DoEvents();
            DataTable table = new DataTable();
            table = ReadFromExcel(filePath, listBox1.SelectedItem.ToString());
            if (table.Columns.Contains("标准编码"))
            {
                table.Columns["标准编码"].ColumnName = "ISBN";
            }
            if (table.Columns.Contains("书名"))
            {
                table.Columns["书名"].ColumnName = "题名";
            }
            if (table.Columns.Contains("正题名"))
            {
                table.Columns["正题名"].ColumnName = "题名";
            }
            if (table.Rows.Count > 0)
            {
                //this.toolStripButton1.Enabled = true;
                this.BookData = new BindingSource();
                this.BookData.DataSource = table;
                this.bindingNavigator1.BindingSource = this.BookData;
                this.excelGridView.DataSource = this.BookData;
                //this.excelGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);//宽度自适应
                //this.excelGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;//宽度自适应
                //this.excelGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;//宽度自适应
                this.ebtBox.Items.Clear();
                for (int i = 0; i < this.excelGridView.ColumnCount; i++)
                {
                    this.ebtBox.Items.Add(this.excelGridView.Columns[i].HeaderText);
                }
                if (this.ebtBox.Items.Count > 0)
                    this.ebtBox.SelectedIndex = 0;
                for (int k = 0; k < this.excelGridView.Columns.Count; k++)
                {
                    string column = this.excelGridView.Columns[k].HeaderText;
                    switch (column)
                    {
                        case "书号":
                            this.excelGridView.Columns["书号"].HeaderText = "ISBN";
                            break;
                        case "条码":
                            this.excelGridView.Columns["条码"].HeaderText = "ISBN";
                            break;
                        case "条码号":
                            this.excelGridView.Columns["条码号"].HeaderText = "ISBN";
                            break;
                        case "标准编码":
                            this.excelGridView.Columns["标准编码"].HeaderText = "ISBN";
                            break;
                        case "isbn":
                            this.excelGridView.Columns["isbn"].HeaderText = "ISBN";
                            break;
                        case "书名":
                            this.excelGridView.Columns["书名"].HeaderText = "题名";
                            break;
                        case "图书名称":
                            this.excelGridView.Columns["图书名称"].HeaderText = "题名";
                            break;
                        case "主题名":
                            this.excelGridView.Columns["主题名"].HeaderText = "题名";
                            break;
                        case "正题名":
                            this.excelGridView.Columns["正题名"].HeaderText = "题名";
                            break;
                        case "定数":
                            this.excelGridView.Columns["定数"].HeaderText = "订数";
                            break;
                        case "价格":
                            this.excelGridView.Columns["价格"].HeaderText = "订价";
                            break;
                        case "定价":
                            this.excelGridView.Columns["定价"].HeaderText = "订价";
                            break;
                        case "主要著作者":
                            this.excelGridView.Columns["主要著作者"].HeaderText = "责任者";
                            break;
                        case "第一责任者":
                            this.excelGridView.Columns["第一责任者"].HeaderText = "责任者";
                            break;
                        case "作者":
                            this.excelGridView.Columns["作者"].HeaderText = "责任者";
                            break;
                        case "第二责任者":
                            this.excelGridView.Columns["第二责任者"].HeaderText = "译者";
                            break;
                        case "指导者":
                            this.excelGridView.Columns["指导者"].HeaderText = "译者";
                            break;
                        case "指导老师":
                            this.excelGridView.Columns["指导老师"].HeaderText = "译者";
                            break;
                        case "出版社":
                            this.excelGridView.Columns["出版社"].HeaderText = "出版者";
                            break;
                        case "出版时间":
                            this.excelGridView.Columns["出版时间"].HeaderText = "出版日期";
                            break;
                        case "专业":
                            this.excelGridView.Columns["专业"].HeaderText = "责任者机构";
                            break;
                        case "中图法分类":
                            this.excelGridView.Columns["中图法分类"].HeaderText = "分类";
                            break;
                        case "学号":
                            this.excelGridView.Columns["学号"].HeaderText = "学工号";
                            break;
                    }
                }
            }
            this.RefMarc();
            wait.Close();
            string time1 = watch.Elapsed.ToString();
            MessageBox.Show("导入：" + table.Rows.Count + "条，耗时：" + time1);
        }
        private void RefMarc()
        {
            if (this.dataGridView1.Rows.Count > 0)
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                    i--;
                }
            }
            for (int i = 0; i < this.excelGridView.ColumnCount; i++)
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[i].Cells[0].Value = this.excelGridView.Columns[i].HeaderText;
                string ht = this.excelGridView.Columns[i].HeaderText;
                switch (ht)
                {
                    case "ISBN":
                        dataGridView1.Rows[i].Cells[1].Value = "010";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "书号":
                        dataGridView1.Rows[i].Cells[1].Value = "010";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "标准编码":
                        dataGridView1.Rows[i].Cells[1].Value = "010";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "订价":
                        dataGridView1.Rows[i].Cells[1].Value = "010";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "d";
                        break;
                    case "单价":
                        dataGridView1.Rows[i].Cells[1].Value = "010";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "d";
                        break;
                    case "装帧":
                        dataGridView1.Rows[i].Cells[1].Value = "010";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "b";
                        break;
                    case "征订号":
                        dataGridView1.Rows[i].Cells[1].Value = "092";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "b";
                        break;
                    case "语种":
                        dataGridView1.Rows[i].Cells[1].Value = "101";
                        dataGridView1.Rows[i].Cells[2].Value = "0 ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "题名":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "1 ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "并列题名":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "b";
                        break;
                    case "副题名":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "e";
                        break;
                    case "分辑号":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "h";
                        break;
                    case "责任者":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "f";
                        break;
                    case "分辑名":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "i";
                        break;
                    case "译者":
                        dataGridView1.Rows[i].Cells[1].Value = "200";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "g";
                        break;
                        break;
                    case "发行地":
                        dataGridView1.Rows[i].Cells[1].Value = "210";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "出版地":
                        dataGridView1.Rows[i].Cells[1].Value = "210";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "出版者":
                        dataGridView1.Rows[i].Cells[1].Value = "210";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "c";
                        break;
                    case "出版日期":
                        dataGridView1.Rows[i].Cells[1].Value = "210";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "d";
                        break;
                    case "页码":
                        dataGridView1.Rows[i].Cells[1].Value = "215";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "丛书项":
                        dataGridView1.Rows[i].Cells[1].Value = "225";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "内容简介":
                        dataGridView1.Rows[i].Cells[1].Value = "330";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "一般性附注":
                        dataGridView1.Rows[i].Cells[1].Value = "300";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "读者对象":
                        dataGridView1.Rows[i].Cells[1].Value = "300";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "开本":
                        dataGridView1.Rows[i].Cells[1].Value = "215";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "d";
                        break;
                    case "图表":
                        dataGridView1.Rows[i].Cells[1].Value = "215";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "c";
                        break;
                    case "版本":
                        dataGridView1.Rows[i].Cells[1].Value = "205";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "作者简介":
                        dataGridView1.Rows[i].Cells[1].Value = "314";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "主题词":
                        dataGridView1.Rows[i].Cells[1].Value = "606";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "L606X":
                        dataGridView1.Rows[i].Cells[1].Value = "606";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "x";
                        break;
                    case "L606J":
                        dataGridView1.Rows[i].Cells[1].Value = "606";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "j";
                        break;
                    case "分类":
                        dataGridView1.Rows[i].Cells[1].Value = "690";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "a";
                        break;
                    case "订数":
                        dataGridView1.Rows[i].Cells[1].Value = "905";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "f";
                        break;
                    case "学工号":
                        dataGridView1.Rows[i].Cells[1].Value = "701";
                        dataGridView1.Rows[i].Cells[2].Value = "  ";
                        dataGridView1.Rows[i].Cells[3].Value = "d";
                        break;
                    case "责任者机构":
                        dataGridView1.Rows[i].Cells[1].Value = "701";
                        dataGridView1.Rows[i].Cells[2].Value = "";
                        dataGridView1.Rows[i].Cells[3].Value = "p";
                        break;
                }
            }
            this.re();
        }
        private void re()
        {
            DataGridViewRow dgvr = this.excelGridView.CurrentRow;
            //DataRowView current = this.BookData.Current as DataRowView;
            if (this.dataGridView1.Rows.Count > 0)
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    if (string.IsNullOrEmpty((string)dataGridView1.Rows[i].Cells[1].Value))
                    {
                        dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                        i--;
                    }
                    //MessageBox.Show("nam0" + '\x001e'.ToString()+(string)dataGridView1.Rows[i].Cells[1].Value+ '\x001f'.ToString()+ (string)dataGridView1.Rows[i].Cells[2].Value);
                }
            }
            if (this.dataGridView1.Rows.Count > 0)
            {
                dt.Clear();
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    if (!string.IsNullOrEmpty((string)dataGridView1.Rows[i].Cells[1].Value))
                    {
                        dt.Rows.Add();
                        dt.Rows[i]["字段标识"] = (string)dataGridView1.Rows[i].Cells[1].Value;
                        dt.Rows[i]["指"] = (string)dataGridView1.Rows[i].Cells[2].Value;
                        string lm = (string)dataGridView1.Rows[i].Cells[0].Value;
                        if (!string.IsNullOrEmpty((string)dataGridView1.Rows[i].Cells[3].Value))
                        {
                            string zzd = (string)dataGridView1.Rows[i].Cells[3].Value;
                            if (!string.IsNullOrEmpty(dgvr.Cells.GetCellValueFromColumnHeader(lm).ToString()))
                            {
                                string nr = dgvr.Cells.GetCellValueFromColumnHeader(lm).ToString();
                                if (!string.IsNullOrEmpty(nr))
                                {
                                    nr = StringUtil.ToDBC(nr).Replace("?","");
                                    dt.Rows[i]["子字段"] = '\x001f'.ToString() + zzd + nr;
                                }
                            }
                        }
                    }
                }
            }
            tabTemp.Clear();
            tabTemp.Dispose();
            FindComValue();
            if (tabTemp.Rows.Count > 0)
            {
                //string id = (BookLocal.GetGcMaxId("主键码", strDBKey) + Convert.ToInt32(current["主键码"].ToString().Trim())).ToString();
                string marc = "nam0" + '\x001e'.ToString() + "001" + "1".PadLeft(2, '0') + DateTime.Now.ToString("yyyy") + "1".PadLeft(6, '0') + '\x001e'.ToString() + "005" + DateTime.Now.ToString("yyyyMMddHHmmss.ff");
                for (int i = 0; i < tabTemp.Rows.Count; i++)
                {
                    if (!string.IsNullOrEmpty(tabTemp.Rows[i]["子字段"].ToString()))
                    {
                        string zsf = tabTemp.Rows[i]["指"].ToString();
                        if (string.IsNullOrEmpty(zsf))
                            zsf = "  ";
                        marc += '\x001e'.ToString() + tabTemp.Rows[i]["字段标识"].ToString() + zsf + tabTemp.Rows[i]["子字段"].ToString();
                    }
                }
                MarcConvert convert = new MarcConvert();
                convert.MarcText = marc;
                convert._kjm = this.kjm;
                convert.autoZD();
                marc = convert.MarcText;
                this.marcGridHS1.MarcType = 1;
                this.marcGridHS1.MarcText = marc;
                //this.marcGridHS1.setPy();
                this.marcGridHS1.SetGridView();
                this.marcText = marc;
            }
        }
        private void FindComValue()
        {
            if (dt.Rows.Count > 0)
            {
                string row1 = dt.Rows[0][0].ToString();//取表的第一行第一列
                DataRow[] drr = dt.Select("字段标识=" + row1);

                DataRow drTemp = tabTemp.NewRow();//临时新的行
                foreach (DataRow row in drr)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        if (i != 0)
                        {
                            if (row[i].ToString().Trim() != "")
                                drTemp[i] = drTemp[i].ToString() + row[i].ToString();//合并每一列的数据
                        }
                        else
                        {
                            drTemp[i] = row[i].ToString();//添加第一列，不需要相加
                        }
                    }
                    dt.Rows.Remove(row);//清除此类的行
                }
                tabTemp.Rows.Add(drTemp);//添加临时新的行数据
                FindComValue();
            }
        }

        private void InsertBook(string marc,List<int> jms,int num)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.InertThread), new Triplet(marc,jms, num));
        }
        private void InertThread(object triplet)
        {
            string marc = (triplet as Triplet).First.ToString();
            List<int> jms  = (List<int>)(triplet as Triplet).Second;
            int num = (int)(triplet as Triplet).Third;
            InserBookWork work = new InserBookWork();
            work.Marc = marc;
            work.jms= jms;
            work.num = num;
            work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.ft_WorkCompleted);
            work.RunWorkerSync(new DoWorkEventArgs(num));
        }
        private void ft_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int num = (sender as InserBookWork).num;
            if (e.Error != null)
            {
                
            }
            else if (e.Cancelled)
            {
                
            }
            else
            {
                this.excelGridView.Rows[num - 1].DefaultCellStyle.ForeColor = System.Drawing.Color.White;
                this.excelGridView.Rows[num-1].DefaultCellStyle.BackColor = System.Drawing.Color.Green;
                if (num==this.excelGridView.Rows.Count)
                    this.Ding();
            }
        }
        private void Ding()
        {
            try
            {
                SoundPlayer player = new SoundPlayer();
                player.SoundLocation = "download_complete.wav"; //把wav音频文件放在exe同目录下就行
                player.Load();//加载
                player.PlaySync();//阻塞进程，播放完毕后才会执行后面的代码
            }
            catch
            {
                
            }
            foreach (System.Windows.Forms.Control control in this.Controls)
            {
                control.Enabled = true;
            }
        }
        private void saveBtn_Click(object sender, EventArgs e)
        {
            foreach (System.Windows.Forms.Control control in this.Controls)
            {
                control.Enabled = false;
            }
            using (DbOperHandler _open = new Common().Doh())
            {
                int size = this.excelGridView.Rows.Count;
                List<int> zjms = FileFunction.getBrokenNumber(size, "馆藏书目库", "主键码");
                List<int> dzjms = FileFunction.getBrokenNumber(size, "馆藏典藏库", "子键码");
                List<int> czjms = FileFunction.getBrokenNumber(size, "采购库", "子键码");
                //Console.WriteLine(size + ":" + zjms.Count);
                FrmUpProgess progess = new FrmUpProgess();
                progess.Show();
                progess.progressBarX1.Maximum = size;
                for (int i = 0; i < size; i++)
                {
                    int zjm, czjm,dzjm;
                    if (i < zjms.Count)
                        zjm = zjms[i];
                    else
                    {
                        _open.Reset();
                        zjm = (int)_open.MaxObject("馆藏书目库", "主键码");
                    }
                    if (i < czjms.Count)
                        czjm = czjms[i];
                    else
                    {
                        _open.Reset();
                        czjm = (int)_open.MaxObject("采购库", "子键码");
                    }
                    if (i < dzjms.Count)
                        dzjm = dzjms[i];
                    else
                    {
                        _open.Reset();
                        dzjm = (int)_open.MaxObject("馆藏典藏库", "子键码");
                    }
                    excelGridView.CurrentCell = excelGridView.Rows[i].Cells[0];
                    this.re();
                    List<int> jms = new List<int> { zjm, czjm, this.kjm};
                    this.InsertBook(this.marcText, jms, i+1);
                    progess.label1.Text = "当前:" + (i+1).ToString();                    
                    Application.DoEvents();
                    progess.progressBarX1.Value = (i+1);
                }
                progess.Close();
            }

            //DialogResult = DialogResult.OK;
            //base.Close();
        }
        private void saveBtn_bak_Click(object sender, EventArgs e)
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                FrmUpProgess progess = new FrmUpProgess();
                int num = 0;
                progess.Show();
                progess.progressBarX1.Maximum = this.excelGridView.Rows.Count;
                for (int i = 0; i < this.excelGridView.Rows.Count; i++)
                {
                    List<int> zjmList = new List<int>();
                    _open.Reset();
                    _open.SqlCmd = " select 子键码 from 采购库 where 子键码>0 order by 子键码";
                    DataTable dcg = _open.GetDataTable();
                    if (dcg.Rows.Count > 0)
                    {
                        for (int j = 0; j < dcg.Rows.Count; j++)
                        {
                            //Console.WriteLine(dcg.Rows[i]["子键码"].ToString());
                            zjmList.Add(Convert.ToInt32(dcg.Rows[j]["子键码"].ToString()));
                        }
                    }
                    int czjm = StringUtil.GetNextNumber(zjmList);
                    List<int> jmList = new List<int>();
                    _open.Reset();
                    _open.SqlCmd = " select 主键码 from 馆藏书目库 where 主键码>0 order by 主键码";
                    DataTable dr = _open.GetDataTable();
                    if (dr.Rows.Count > 0)
                    {
                        for (int j = 0; j < dr.Rows.Count; j++)
                        {
                            jmList.Add(Convert.ToInt32(dr.Rows[j]["主键码"].ToString()));
                        }
                    }
                    int zjm = StringUtil.GetNextNumber(jmList);
                    //excelGridView.Rows[i].Selected = true;
                    excelGridView.CurrentCell = excelGridView.Rows[i].Cells[0];
                    this.re();
                    MarcConvert convert = new MarcConvert();
                    convert.MarcText = this.marcText;
                    string isbn = convert.GetASubField("010", "a", 1);
                    _open.Reset();
                    if (!string.IsNullOrEmpty(isbn))
                    {
                        string sisbn = StringUtil.BuingISBNSept(StringUtil.BarCodeToISBN(isbn.Replace("-", "")));
                        _open.AddFieldItem("标准编码", isbn);
                    }
                    string ydj = convert.GetASubField("010", "d", 1);
                    double dj = StringUtil.GetDj(ydj);
                    if (dj == 0.00)
                        dj = 5.00;
                    string title = convert.GetASubField("200", "a", 1);
                    if (!string.IsNullOrEmpty(title))
                    {
                        title = StringUtil.ToDBC(title).Replace(@"'","\'");
                        _open.AddFieldItem("主键码", zjm);
                        string press = convert.GetASubField("210", "c", 1);
                        if (!string.IsNullOrEmpty(press))
                        {
                            press = StringUtil.ToDBC(press).Replace(@"'", "\'");
                            _open.AddFieldItem("出版者", press);
                        }
                        string pdate = convert.GetASubField("210", "d", 1);
                        if (!string.IsNullOrEmpty(pdate))
                        {
                            pdate= StringUtil.ToDBC(pdate).Replace(@"'", "\'");
                            _open.AddFieldItem("出版日期", pdate);
                        }
                        else
                        {
                            pdate = DateTime.Now.Year.ToString();
                        }
                        string author = convert.GetASubField("200", "f", 1);
                        if (!string.IsNullOrEmpty(author))
                        {
                            author = StringUtil.ToDBC(author).Replace(@"'", "\'");
                            _open.AddFieldItem("责任者", author);
                        }
                        string zrjg = convert.GetASubField("701", "p", 1);
                        if (!string.IsNullOrEmpty(zrjg))
                        {
                            zrjg = StringUtil.ToDBC(zrjg).Replace(@"'", "\'");
                            _open.AddFieldItem("责任者单位", zrjg);
                        }
                        string xgh = convert.GetASubField("701", "d", 1);
                        if (!string.IsNullOrEmpty(xgh))
                        {
                            xgh = StringUtil.ToDBC(xgh).Replace(@"'", "\'");
                            _open.AddFieldItem("学工号", xgh);
                            progess.label1.Text = "当前:" + xgh;
                        }
                        _open.AddFieldItem("题名", title);
                        _open.AddFieldItem("库键码", this.kjm);
                        _open.AddFieldItem("处理日期", DateTool.stringToDate(pdate+"-09-20", DateTool.formatDate2));
                        _open.AddFieldItem("marc", this.marcText.Replace(@"'", "\'"));
                        try
                        {
                            _open.Insert("馆藏书目库");
                            //Console.WriteLine("新增馆藏ID:"+zjm + ":::" + czjm);
                            _open.Reset();
                            _open.SqlCmd = "SET IDENTITY_INSERT 采购库 ON ";
                            _open.ExecuteSqlNonQuery();
                            _open.Reset();
                            _open.AddFieldItem("子键码", czjm);
                            _open.AddFieldItem("主键码", zjm);
                            _open.AddFieldItem("库键码", this.kjm);
                            _open.AddFieldItem("发行商键码", 1);
                            _open.AddFieldItem("经费来源键码", 0);
                            _open.AddFieldItem("单价", dj);
                            _open.AddFieldItem("馆键码", 1);
                            _open.AddFieldItem("入藏日期", DateTool.stringToDate(pdate + "-09-20", DateTool.formatDate2));
                            _open.AddFieldItem("状态", "G");
                            _open.Insert("采购库");
                            _open.Reset();
                            _open.SqlCmd = "SET IDENTITY_INSERT 采购库 OFF ";
                            _open.ExecuteSqlNonQuery();
                            this.excelGridView.Rows.RemoveAt(i);
                            i--;
                        }
                        catch(OleDbException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    num++;
                    Application.DoEvents();
                    progess.progressBarX1.Value = num;
                }
                progess.Close();
            }
            
            //DialogResult = DialogResult.OK;
            //base.Close();
        }

        private void FrmGcExcelImp_Load(object sender, EventArgs e)
        {
            sBox.SelectedIndex = 0;
        }

        private void dgb_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == -1 || e.RowIndex == -1)
                {
                    return;
                }
                DataGridViewCell cell = this.excelGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                excelGridView.CurrentCell = excelGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                this.re();                
            }
            catch (Exception ex)
            {
            }
        }
    }
}
